<template>
  <div class="front-matter-manager">
    <div class="header">
      <div class="title">选择将导出在目录之前的页面</div>
      <div class="tips">已选页面将按右侧顺序导出，默认不显示访视名称</div>
    </div>

    <div class="body">
      <div class="left-panel">
        <div class="panel-head">
          <el-input
            v-model="keyword"
            placeholder="搜索表单名称"
            clearable
            :prefix-icon="Search"
          />
        </div>

        <div class="panel-content">
          <el-empty v-if="loading" description="正在加载表单..." />
          <template v-else>
            <el-scrollbar height="420px">
              <div v-if="filteredForms.length === 0" class="empty-hint">未找到可添加的表单</div>
              <div
                v-for="form in filteredForms"
                :key="form._id || form.id"
                class="form-item"
              >
                <div class="meta">
                  <div class="name">{{ form.name }}</div>
                  <div class="sub">ID: {{ form._id || form.id }}</div>
                </div>
                <el-button
                  size="small"
                  :disabled="selectedIds.includes(String(form._id || form.id))"
                  @click="addToSelected(form)"
                >加入</el-button>
              </div>
            </el-scrollbar>
          </template>
        </div>
      </div>

      <div class="right-panel">
        <div class="panel-head">
          <div class="title-small">前置页（{{ selectedIds.length }}）</div>
          <div class="actions">
            <el-button link type="danger" @click="clearAll" :disabled="selectedIds.length===0">清空</el-button>
          </div>
        </div>
        <div class="panel-content">
          <el-empty v-if="selectedIds.length===0" description="将左侧表单加入到这里" />
          <el-scrollbar v-else height="420px">
            <div
              v-for="(fid, idx) in selectedIds"
              :key="fid"
              class="selected-item"
            >
              <div class="meta">
                <div class="name">{{ findFormName(fid) }}</div>
                <div class="sub">ID: {{ fid }}</div>
                <div class="props">
                  <el-checkbox v-model="itemProps[fid].showInToc">显示在目录</el-checkbox>
                  <el-select v-model="itemProps[fid].tocLevel" size="small" style="width: 88px; margin-left: 8px;" :disabled="!itemProps[fid].showInToc">
                    <el-option :value="1" label="目录1级" />
                    <el-option :value="2" label="目录2级" />
                  </el-select>
                  <el-checkbox v-model="itemProps[fid].pageBreakAfter" style="margin-left:8px;">末尾分页</el-checkbox>
                  <el-checkbox v-model="itemProps[fid].hideFormTitle" style="margin-left:8px;">不导出表单名称</el-checkbox>
                </div>
              </div>
              <div class="ops">
                <el-button circle size="small" :icon="Top" @click="moveTop(idx)" :disabled="idx===0" />
                <el-button circle size="small" :icon="ArrowUp" @click="moveUp(idx)" :disabled="idx===0" />
                <el-button circle size="small" :icon="ArrowDown" @click="moveDown(idx)" :disabled="idx===selectedIds.length-1" />
                <el-button circle size="small" :icon="Delete" type="danger" @click="removeAt(idx)" />
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>

    <div class="footer">
      <el-button @click="emit('close')">取消</el-button>
      <el-button type="primary" @click="confirm" :disabled="confirming">确定</el-button>
    </div>
  </div>
  
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Search, ArrowUp, ArrowDown, Delete, Top } from '@element-plus/icons-vue'
import { useFormStore } from '@/stores/form'

const props = defineProps({
  projectId: {
    type: [String, Number],
    required: true
  },
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['close', 'confirm', 'update:modelValue'])

const formStore = useFormStore()
const loading = ref(false)
const keyword = ref('')
const allForms = ref([])
const selectedIds = ref([])
const itemProps = ref({})
const confirming = ref(false)

const fetchForms = async () => {
  loading.value = true
  try {
    const { data } = await formStore.getAllForms({ projectId: props.projectId })
    allForms.value = data || formStore.getForms || []
  } catch (e) {
    allForms.value = formStore.getForms || []
  } finally {
    loading.value = false
  }
}

const filteredForms = computed(() => {
  const k = keyword.value.trim().toLowerCase()
  const selectedSet = new Set(selectedIds.value)
  return (allForms.value || [])
    .filter(f => !selectedSet.has(String(f._id || f.id)))
    .filter(f => !k || String(f.name || '').toLowerCase().includes(k))
})

const addToSelected = (form) => {
  const id = String(form._id || form.id)
  if (!selectedIds.value.includes(id)) {
    selectedIds.value.push(id)
    if (!itemProps.value[id]) {
      itemProps.value[id] = { showInToc: false, tocLevel: 1, pageBreakAfter: true, hideFormTitle: true }
    }
    emit('update:modelValue', [...selectedIds.value])
  }
}

const removeAt = (idx) => {
  const id = selectedIds.value[idx]
  selectedIds.value.splice(idx, 1)
  delete itemProps.value[id]
  emit('update:modelValue', [...selectedIds.value])
}

const moveUp = (idx) => {
  if (idx <= 0) return
  const arr = selectedIds.value
  const [x] = arr.splice(idx, 1)
  arr.splice(idx - 1, 0, x)
  emit('update:modelValue', [...arr])
}

const moveDown = (idx) => {
  const arr = selectedIds.value
  if (idx >= arr.length - 1) return
  const [x] = arr.splice(idx, 1)
  arr.splice(idx + 1, 0, x)
  emit('update:modelValue', [...arr])
}

const moveTop = (idx) => {
  if (idx === 0) return
  const arr = selectedIds.value
  const [x] = arr.splice(idx, 1)
  arr.unshift(x)
  emit('update:modelValue', [...arr])
}

const clearAll = () => {
  selectedIds.value = []
  itemProps.value = {}
  emit('update:modelValue', [])
}

const confirm = async () => {
  confirming.value = true
  const frontMatter = selectedIds.value.map((fid, idx) => {
    const p = itemProps.value[fid] || {}
    // 明确排除已删除的“自定义标题”
    const { showInToc = false, tocLevel = 1, pageBreakAfter = true, hideFormTitle = true } = p
    return { formId: fid, order: idx, showInToc, tocLevel, pageBreakAfter, hideFormTitle }
  })
  emit('confirm', { frontMatter })
  confirming.value = false
}

const findFormName = (fid) => {
  const f = (allForms.value || []).find(x => String(x._id || x.id) === String(fid))
  return f?.name || '未命名表单'
}

const resetFromModel = () => {
  if (Array.isArray(props.modelValue) && props.modelValue.length > 0 && typeof props.modelValue[0] === 'object') {
    // 完整对象数组
    selectedIds.value = props.modelValue.map(x => String(x.formId))
    const map = {}
    props.modelValue.forEach(x => {
      map[String(x.formId)] = {
        showInToc: !!x.showInToc,
        tocLevel: [1,2].includes(x.tocLevel) ? x.tocLevel : 1,
        pageBreakAfter: x.pageBreakAfter !== false,
        hideFormTitle: x.hideFormTitle !== false
      }
    })
    itemProps.value = map
  } else {
    const valid = Array.isArray(props.modelValue) ? props.modelValue.map(x => String(x)) : []
    selectedIds.value = [...valid]
    const map = {}
    valid.forEach(fid => { map[fid] = { showInToc: false, tocLevel: 1, pageBreakAfter: true } })
    itemProps.value = map
  }
}

watch(() => props.modelValue, resetFromModel, { immediate: true })

onMounted(() => {
  fetchForms()
})
</script>

<style scoped>
.front-matter-manager {
  width: 100%;
}
.header {
  padding: 6px 2px 12px 2px;
}
.header .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.header .tips {
  margin-top: 4px;
  color: #909399;
  font-size: 12px;
}
.body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}
.left-panel, .right-panel {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fff;
  min-height: 480px;
  display: flex;
  flex-direction: column;
}
.panel-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}
.panel-head .title-small {
  font-weight: 600;
}
.panel-content {
  padding: 8px;
  flex: 1;
}
.form-item, .selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 10px;
  border: 1px solid #f2f6fc;
  border-radius: 4px;
  margin-bottom: 8px;
}
.form-item .meta, .selected-item .meta {
  display: flex;
  flex-direction: column;
}
.name { font-weight: 500; color: #303133; }
.sub { color: #909399; font-size: 12px; }
.selected-item .ops { display: flex; gap: 6px; }
.empty-hint { color: #909399; padding: 12px; }
.footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
}
</style>


